#include <iostream>
#include <set>
#include <utility>
#include <vector>

using std::cout;
using std::endl;
using std::set;
using std::pair;
using std::vector;

template <typename Container>
void display(const Container &con)
{
    for(auto &elem : con)
    {
        cout << elem << "  ";
    }
    cout << endl;
}

void test()
{
    //set的特征：
    //1、存放的是key类型，key值是唯一的，不能重复
    //2、默认情况下，会按照key值进行升序排列
    //3、set的底层使用的是红黑树结构
    set<int> number={1, 3, 5, 8, 9, 7, 3, 6, 5, 2};
    //set<int, std::greater<int> > number{1, 3, 5, 8, 9, 7, 3, 6, 5, 2};
    display(number);

    cout << endl << "count查找" << endl;
    size_t cnt = number.count(3);
    cout << "cnt = " << cnt << endl;

    cout << endl << "find查找" << endl;
    set<int>::iterator it = number.find(4);
    if(it != number.end())
    {
        cout << "该元素在set中" << *it << endl;
    }
    else
    {
        cout << "该元素不在set中" << endl;
    }

    cout << endl << "insert插入" << endl;
    pair<set<int>::iterator, bool> ret = number.insert(10);
    if(ret.second)
    {
        cout << "插入成功 " << *ret.first <<endl;
    }
    else
    {
        cout << "插入失败，元素已经存在set中" << endl;
    }

    cout << endl;
    //迭代器范围地插入
    vector<int> vec = {1, 3, 5, 9, 11, 34, 67, 4, 2};
    number.insert(vec.begin(), vec.end());
    display(number);

    cout << endl;
    //大括号插入
    number.insert({12, 88, 33});
    display(number);

    cout << endl << "删除操作" << endl;
    it = number.begin();
    ++it;
    ++it;
    cout << "*it = " << *it << endl;
    number.erase(it);
    display(number);
    number.erase(5);
    display(number);

    cout << endl << "set不支持下标访问" << endl;
    /* cout << "number[1] = " << number[1] << endl; */

    cout << endl << "不支持修改，因为set是红黑树，修改了容易乱" << endl;
    it = number.begin();
    ++it;
    ++it;
    cout << "*it = " << *it << endl;
    /* *it = 100;//error */
}

int main(int argc, char *argv[])
{
    test();
    return 0;
}


